(
  ($)->

    class Data
      constructor:(@url)->
        @dataType = 'json'

      setUrl:(@url)->
        @

      setDataType:(@dataType = 'json')->
        @

      get: (params1,callback,isCache = true)->
        _this = this
        actionUrl = @url
        data = @cache(actionUrl,params1)
        if typeof(data) is 'undefined'
          $.get actionUrl,params1,(data)->
            _this.cache(actionUrl,params1,data) if isCache
            callback(data)
          ,@dataType
        else
          callback(data)

      cache: (actionUrl,params,v = null)->
        hash = @getHashCode(actionUrl)
        hash += @getHashCode(params)
        if v is null then $.data(document,hash) else $.data(document,hash,v)

      getHashCode: (mix, caseSensitive)->
        `
            type = $.type(mix);
            if (type == "array") {
                mix = mix.toString();
            } else if (type == "object") {
                try {
                    mix = JSON.stringify(mix);
                } catch (e) {
                    throw new Error('getHashCode Error!');
                }
            }
            if (!caseSensitive) {
                mix = mix.toLowerCase();
            }
            // 1315423911=b'1001110011001111100011010100111'
            var hash = 1315423911, i, ch;
            for (i = mix.length - 1; i >= 0; i--) {
                ch = mix.charCodeAt(i);
                hash ^= ((hash << 5) + ch + (hash >> 2));
            }
        `
        (hash & 0x7FFFFFFF).toString()


    $.fn.JScrollLoading = (config)->
      ele = @
      initConfig = {
        url:''
        page:2
        loading:'#loading'
        #滚动条距离页面底部的距离
        bottom:100
        #返回的数据类型
        dataType:'html'
        #是否停止
        stop:false
        callback:->
      }
      config = $.extend({},initConfig,config)

      sl = {

        lock:false

        Data:(new Data(config.url)).setDataType('html')

        getData:(callback=->)->
          @Data.get {page:config.page},callback
          @


        getBottomHeight:->
          #获取距离底部的距离
          $(document).height() - $(document).scrollTop() - $(window).height()

        scroll:->
          if !config.stop and !this.lock and this.getBottomHeight() <= config.bottom
            #加锁
            this.lock = true
            this.loading()

        loading:->
          _this = this
          $(config.loading).show()
          this.getData (data)->

            config.page += 1

            config.callback(data) if data isnt ''

            $(config.loading).hide()
            #解锁
            _this.lock = false

            config.stop = true if data is ''



        listen:->
          $(ele).bind 'scroll', =>
            @scroll()
          this
      }

      sl.listen()


)(jQuery)